import os
import re
from xml.dom import minidom

doc_path = "C/"
doc_name = "main.pdf"
top_path = "/media/disk/D/"

os.popen("rm -rf " +doc_path+ "*.svg").read()

file_lines = os.popen("pdfinfo " + doc_path + doc_name).read().strip().split("\n")
file_lines = map(lambda x:x.split(":"), file_lines)
file_props = {}
for line in file_lines:
    file_props[line[0]] = " ".join(line[1:]).strip()

for page in range(int(file_props['Pages'])):
    os.popen("pdf2svg " + doc_path + doc_name + " " + doc_path + "source_" + str(page+1) + ".svg" + " " + str(page+1)).read()

sketches = os.listdir(top_path)
sketches.sort()
for sketch in sketches:
    notepad = sketch[0]
    page = int(sketch[1:-4])
    os.popen("python top2svg.py " + top_path + notepad + ("%.2d" % page) +".TOP > " + doc_path + "out_" + str(page) + ".svg").read()


out_files = os.listdir(doc_path)
out_files = map(lambda file_name: re.search("(\d+)", file_name), out_files)
out_files = filter(lambda file_match: file_match, out_files)
out_files = map(lambda file_match: int(file_match.group(0)), out_files)
out_files = set(out_files)
out_files = [page_number for page_number in out_files]
out_files.sort()

for page in out_files:
    in_file = file(doc_path + "source_" + str(page) + ".svg", "rb")
    in_doc = minidom.parse(in_file)
    if (os.path.exists(doc_path + "out_" + str(page) + ".svg")):
        sk_file = file(doc_path + "out_" + str(page) + ".svg", "rb")
        sk_doc = minidom.parse(sk_file)
        for sk_node in sk_doc.childNodes[1].childNodes:
            imported_node = in_doc.importNode(sk_node, True)
            in_doc.childNodes[0].appendChild(imported_node)
    open(doc_path + "merged_" + str(page) + ".svg", "w").write(in_doc.toxml())
